package com.ruoyi.pos.service.impl.system;

import com.ruoyi.pos.domain.system.PosSystemConfig;
import com.ruoyi.pos.domain.dto.system.request.SystemConfigQueryRequest;
import com.ruoyi.pos.domain.dto.system.request.SystemConfigUpdateRequest;
import com.ruoyi.pos.domain.dto.system.response.SystemConfigResponse;
import com.ruoyi.pos.domain.dto.common.response.BasePageResponse;
import com.ruoyi.pos.mapper.system.PosSystemConfigMapper;
import com.ruoyi.pos.service.system.IPosSystemConfigService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * POS系统配置Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-30
 */
@Service
@Transactional(transactionManager = "posTransactionManager")
public class PosSystemConfigServiceImpl implements IPosSystemConfigService {

    private static final Logger logger = LoggerFactory.getLogger(PosSystemConfigServiceImpl.class);

    @Autowired
    private PosSystemConfigMapper posSystemConfigMapper;

    /**
     * 查询单个系统配置信息
     * 支持根据ID、配置键查询
     * 
     * @param request 查询请求
     * @return 系统配置信息
     */
    @Override
    public SystemConfigResponse getSystemConfig(SystemConfigQueryRequest request) {
        PosSystemConfig systemConfig = null;
        
        if (request.getConfigId() != null) {
            systemConfig = posSystemConfigMapper.selectPosSystemConfigById(request.getConfigId());
        } else if (StringUtils.isNotEmpty(request.getConfigKey())) {
            systemConfig = posSystemConfigMapper.selectPosSystemConfigByKey(request.getConfigKey());
        }
        
        if (systemConfig == null) {
            return null;
        }
        
        return convertToResponse(systemConfig);
    }

    /**
     * 分页查询系统配置列表
     * 
     * @param request 查询请求
     * @return 分页响应
     */
    @Override
    public BasePageResponse<SystemConfigResponse> querySystemConfigs(SystemConfigQueryRequest request) {
        PosSystemConfig systemConfig = new PosSystemConfig();
        systemConfig.setConfigId(request.getConfigId());
        systemConfig.setConfigKey(request.getConfigKey());
        systemConfig.setConfigName(request.getConfigName());
        systemConfig.setConfigType(request.getConfigType());
        systemConfig.setStatus(request.getIsEnabled());
        
        List<PosSystemConfig> systemConfigs = posSystemConfigMapper.selectPosSystemConfigList(systemConfig);
        List<SystemConfigResponse> responses = systemConfigs.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
        
        return new BasePageResponse<>(responses, systemConfigs.size());
    }

    /**
     * 批量更新系统配置
     * 
     * @param request 更新请求
     * @return 是否成功
     */
    @Override
    public boolean updateSystemConfigs(SystemConfigUpdateRequest request) {
        try {
            for (SystemConfigUpdateRequest.ConfigItem item : request.getConfigItems()) {
                PosSystemConfig systemConfig = new PosSystemConfig();
                systemConfig.setConfigId(item.getConfigId());
                systemConfig.setConfigKey(item.getConfigKey());
                systemConfig.setConfigValue(item.getConfigValue());
                systemConfig.setRemark(item.getConfigDescription());
                systemConfig.setUpdateTime(new Date());
                
                posSystemConfigMapper.updatePosSystemConfig(systemConfig);
            }
            return true;
        } catch (Exception e) {
            logger.error("批量更新系统配置失败", e);
            return false;
        }
    }

    /**
     * 获取系统配置值
     * 
     * @param configKey 配置键
     * @return 配置值
     */
    @Override
    public String getConfigValue(String configKey) {
        PosSystemConfig systemConfig = posSystemConfigMapper.selectPosSystemConfigByKey(configKey);
        return systemConfig != null ? systemConfig.getConfigValue() : null;
    }

    /**
     * 获取系统配置值（带默认值）
     * 
     * @param configKey 配置键
     * @param defaultValue 默认值
     * @return 配置值
     */
    @Override
    public String getConfigValue(String configKey, String defaultValue) {
        String value = getConfigValue(configKey);
        return StringUtils.isNotEmpty(value) ? value : defaultValue;
    }

    /**
     * 转换实体为响应DTO
     * 
     * @param systemConfig 系统配置实体
     * @return 系统配置响应DTO
     */
    private SystemConfigResponse convertToResponse(PosSystemConfig systemConfig) {
        SystemConfigResponse response = new SystemConfigResponse();
        BeanUtils.copyBeanProp(response, systemConfig);
        return response;
    }
}
